package cn.eric.framework.auth.utils;

import cn.eric.framework.auth.domain.User;
import cn.eric.framework.exception.domain.exception.BusinessException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用于鉴权的拦截器
 */
public class EAuthInterceptor implements HandlerInterceptor {
    @Resource
    private int beNoLogin;
    @Resource
    private int beNeedMoreAuthority;
    @Resource
    private EAuthUtil util;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        HttpSession session = httpServletRequest.getSession();
        User user = util.getUser(httpServletRequest, session);

        List<String> authorityIds = EAuthRuleMap.getNeededAuthorityIds(uri);

        if (authorityIds == null || authorityIds.size() == 0) {
            return true;
        }

        if (user == null) {
            throw new BusinessException(beNoLogin);
        }

        List<String> authorityIdsHad = user.getAuthorityIds();

        if (!util.isAuthorityEnough(authorityIdsHad, authorityIds)) {
            throw new BusinessException(beNeedMoreAuthority);
        }

        return true;
        /**
         * todo
         * 1. 获得url的权限或列表
         * 2. 获得用户的User对象
         * 3. 比较是否符合权限要求
         * 3.1 完全匹配
         * 3.2 匹配上级权限 如 权限 1.2 符合 1.2.X(...)X 的权限要求
         * 3.3 匹配角色 (暂时不实现)
         */
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
